package com.luoqiu.cinema.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luoqiu.cinema.common.PageParam;
import com.luoqiu.cinema.common.PageResult;
import com.luoqiu.cinema.common.Result;
import com.luoqiu.cinema.eitityExtends.TicketEx;
import com.luoqiu.cinema.entity.MoviePlace;
import com.luoqiu.cinema.entity.UserInfo;
import com.luoqiu.cinema.mapper.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ManageService {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private TicketMapper ticketMapper;
    @Resource
    private TicketUserMapper ticketUserMapper;
    @Resource
    private MoviePlaceMapper moviePlaceMapper;
    @Resource
    private MoviePlaceMovieMapper moviePlaceMovieMapper;

    public Result<PageResult<UserInfo>> list(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getRows());
        List<UserInfo> infos = userInfoMapper.loadAll(pageParam.getKeyword());
        PageInfo<UserInfo> pageInfo = new PageInfo<>(infos);
        PageResult<UserInfo> pageResult = new PageResult<>();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setData(infos);
        return Result.success(pageResult);
    }

    public Result<String> del(Integer id) {
        userInfoMapper.deleteByPrimaryKey(id);
        List<TicketEx> ticketExes = ticketUserMapper.loadByUserId(id);
        ticketExes.forEach(e -> {
            Integer ticketId = e.getTicketId();
            Integer ticketNum = e.getTicketNum();
            ticketMapper.updateSurplus(ticketId, ticketNum);
        });
        return Result.success(null);
    }

    public Result<PageResult<MoviePlace>> listP(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getRows());
        List<MoviePlace> moviePlaces = moviePlaceMapper.loadByAll(pageParam.getKeyword());
        PageInfo<MoviePlace> pageInfo = new PageInfo<>(moviePlaces);
        PageResult<MoviePlace> pageResult = new PageResult<>();
        pageResult.setData(moviePlaces);
        pageResult.setTotal(pageInfo.getTotal());
        return Result.success(pageResult);
    }

    public Result<String> addP(MoviePlace moviePlace) {
        if (moviePlace.getId() == null) {
            moviePlaceMapper.insertSelective(moviePlace);
        } else {
            moviePlaceMapper.updateByPrimaryKeySelective(moviePlace);
        }
        return Result.success(null);
    }

    public Result<String> delP(Integer id) {
        moviePlaceMapper.deleteByPrimaryKey(id);
        ticketUserMapper.delByPlaceId(id);
        ticketMapper.delByPlaceId(id);
        moviePlaceMovieMapper.delByPlaceId(id);
        return Result.success(null);
    }
}
